package handle

import (
	"git.oschina.net/cnjack/z_app_server/tool"
	"github.com/martini-contrib/render"
	"net/http"
	"strconv"
	"time"
)

func LoginHandle(r render.Render, req *http.Request, resp http.ResponseWriter) {
	req.ParseForm()
	var err error
	var user = req.PostFormValue("user")
	var pass = req.PostFormValue("pass")
	if user == "" || pass == "" {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": "user or pass is empty",
		})
		return
	}
	memberInfo, err := memberModel.FindOne(user)
	if err != nil {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": err.Error(),
		})
		return
	}
	if memberInfo == nil {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": "not find user",
		})
		return
	}
	if pass != memberInfo.Pass {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": "pass is not true",
		})
		return
	}
	var TokenTime = strconv.Itoa(int(time.Now().Unix()))
	aesEnc := tool.AesEncrypt{Key: "435nvyw8nc8nycn34ynci8ycn5gyc983"}
	token := aesEnc.Encrypt(user + pass + TokenTime)
	err = memberInfo.UpdateToken(token, memberInfo.Id)
	if err != nil {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": err.Error(),
		})
		return
	}
	//resp.Header().Add("token", token)
	//resp.Header().Add("token_time", TokenTime)
	resp.Header().Add("Custom-Header", token+":"+TokenTime)
	r.JSON(200, map[string]interface{}{
		"code":      "0",
		"info":      "",
		"user_name": memberInfo.Name,
	})
	return
}
func AutologinHandle(r render.Render, req *http.Request, resp http.ResponseWriter) {

	r.JSON(200, map[string]interface{}{
		"code":       "0",
		"info":       "",
		"token":      resp.Header().Get("token"),
		"token_time": resp.Header().Get("token_time"),
	})
	return
}
func RegistHandle(r render.Render, req *http.Request) {
	var err error
	var user = req.FormValue("user")
	var pass = req.FormValue("pass")
	if user == "" || pass == "" {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": "user or pass is empty",
		})
		return
	}
	err = memberModel.Add(user, pass)
	if err != nil {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": err.Error(),
		})
		return
	}
	r.JSON(200, map[string]interface{}{
		"code": "0",
		"info": "",
	})
}
